package com.huicoo.forestmanager.util;

import android.os.Environment;
import android.text.TextUtils;

import com.huicoo.forestmanager.ui.patrol.forestCampTask.contract.ForestCampTaskVerifyEventContract;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 *
 */
public class AttachmentHelper {
    public static String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ForestManager/attachment/";

    public static String getFilePath(String fileName) {
        File root = new File(rootPath);
        if (!root.exists()) {
            root.mkdirs();
        }
        return rootPath + fileName;
    }

    public static File createFile(String fileName) {
        File file;
        String state = Environment.getExternalStorageState();

        if (state.equals(Environment.MEDIA_MOUNTED)) {
            file = new File(rootPath + fileName);
            LogUtils.v("gogogo file path = " + file.getAbsolutePath());
        } else {
            return null;
        }

        return file;
    }

    public static String getFileName(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return "";
        }
        return filePath.replace(rootPath, "");
    }

    public static void writeFile2Disk(Response<ResponseBody> response, File file, ForestCampTaskVerifyEventContract.FileDownloadCallBack httpCallBack) {

        long currentLength = 0;
        OutputStream os = null;

        InputStream is = response.body().byteStream();
        long totalLength = response.body().contentLength();

        try {

            os = new FileOutputStream(file);

            int len;

            byte[] buff = new byte[2048];

            while ((len = is.read(buff)) != -1) {

                os.write(buff, 0, len);
                currentLength += len;
                LogUtils.v("gogogo 下载当前进度:" + currentLength);
                httpCallBack.onLoading(currentLength, totalLength);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static boolean deleteFile(String filePath) {
        boolean isDelete = false;
        File file = new File(filePath);
        if (file.exists()) {
            isDelete = file.delete();
        }
        return isDelete;
    }

}